/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.api.runtime.task.operator;

import com.google.common.base.Strings;
import com.je.bpm.api.runtime.task.impl.APITaskConverter;
import com.je.bpm.api.runtime.task.operator.desc.TaskSubmitParamDesc;
import com.je.bpm.api.runtime.task.operator.validator.TaskSubmitOperatorValidator;
import com.je.bpm.common.operation.OperatorEnum;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.task.KaiteLoopUserTask;
import com.je.bpm.core.model.task.KaiteTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.RepositoryService;
import com.je.bpm.engine.TaskService;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.task.Task;
import com.je.bpm.engine.task.TaskQuery;
import com.je.bpm.engine.upcoming.ActivitiUpcomingRun;
import com.je.bpm.model.task.payloads.TaskSubmitPayload;
import com.je.bpm.model.task.result.TaskListResult;
import com.je.bpm.runtime.shared.operator.AbstractOperator;
import com.je.bpm.runtime.shared.operator.desc.OperationParamDesc;
import com.je.bpm.runtime.shared.operator.validator.OperatorPayloadParamsValidator;
import com.je.bpm.runtime.task.operator.TaskSubmitOperator;

import java.util.List;
import java.util.Map;

/**
 * 任务提交操作
 */
public class TaskSubmitOperatorImpl extends AbstractOperator<TaskSubmitPayload, TaskListResult> implements TaskSubmitOperator {

    private APITaskConverter apiTaskConverter;
    private TaskService taskService;
    private OperatorPayloadParamsValidator<TaskSubmitPayload> validator;
    private RepositoryService repositoryService;
    private ActivitiUpcomingRun activitiUpcomingRun;

    public TaskSubmitOperatorImpl(APITaskConverter apiTaskConverter, TaskService taskService, RepositoryService repositoryService,
                                  ActivitiUpcomingRun activitiUpcomingRun) {
        this.validator = new TaskSubmitOperatorValidator();
        this.apiTaskConverter = apiTaskConverter;
        this.taskService = taskService;
        this.repositoryService = repositoryService;
        this.activitiUpcomingRun = activitiUpcomingRun;
    }

    @Override
    public String getId() {
        return OperatorEnum.TASK_SUBMIT_OPERATOR.getId();
    }

    @Override
    public String getName() {
        return OperatorEnum.TASK_SUBMIT_OPERATOR.getName();
    }

    @Override
    public OperationParamDesc getParamDesc() {
        return new TaskSubmitParamDesc();
    }

    @Override
    public TaskListResult execute(TaskSubmitPayload taskSubmitPayload) {
        //检查流程是否已经提交
        TaskQuery taskQuery = taskService.createTaskQuery().taskId(taskSubmitPayload.getTaskId());
        List<Task> list = taskQuery.list();
        if (list.size() == 0) {
            throw new ActivitiException(String.format("Can't find task definiton from the process"));
        }
        Task task = list.get(0);
        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());
        FlowElement taskFlowElement = bpmnModel.getFlowElement(task.getTaskDefinitionKey());
        if (taskFlowElement == null) {
            throw new ActivitiException(String.format("Can't find task %s definiton from the process.", task.getName()));
        }

        KaiteTask kaiteTask = (KaiteTask) taskFlowElement;
        String nodeId = taskSubmitPayload.getNodeId();
        //自由节点
        if (kaiteTask instanceof KaiteLoopUserTask && !Strings.isNullOrEmpty(nodeId) && nodeId.equals(kaiteTask.getId())) {
            taskService.loop(taskSubmitPayload.getTaskId(), taskSubmitPayload.getAssignee());
            return null;
        }
        //节点提交完成操作
        taskService.complete(taskSubmitPayload.getTaskId(), taskSubmitPayload.getAssignee(), taskSubmitPayload.getTarget(),
                taskSubmitPayload.getProd(), taskSubmitPayload.getBean(), taskSubmitPayload.getComment(), taskSubmitPayload.getSequentials(), taskSubmitPayload.getIsJump());
        TaskListResult result = new TaskListResult(taskSubmitPayload, null);
        return result;
    }

    @Override
    public TaskSubmitPayload paramsParse(Map<String, Object> params) {
        TaskSubmitPayload taskSubmitPayload = new TaskSubmitPayload(
                formatString(params.get(AbstractOperator.PROD)),
                formatString(params.get("piid")),
                formatString(params.get("taskId")),
                formatString(params.get("beanId")),
                formatString(params.get("assignee")),
                formatString(params.get("target")),
                formatString(params.get("nodeId")),
                params.get(AbstractOperator.BEAN) == null ? null : (Map<String, Object>) params.get(AbstractOperator.BEAN),
                formatString(params.get(CommandContext.IS_JUMP))
                );
        taskSubmitPayload.setComment(params.get("comment") == null ? "同意" : (String) params.get("comment"));
        taskSubmitPayload.setSequentials(formatString(params.get("sequentials")));
        return taskSubmitPayload;
    }

    @Override
    public OperatorPayloadParamsValidator<TaskSubmitPayload> getValidator() {
        return validator;
    }

}
